package com.xhh.nphm.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.xhh.nphm.common.constant.UserConstants;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.Ztree;
import com.xhh.nphm.common.core.domain.entity.Dept;
import com.xhh.nphm.common.core.page.PageDomain;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.core.page.TableSupport;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.common.utils.sql.SqlUtil;
import com.xhh.nphm.system.domain.AppealCate;
import com.xhh.nphm.system.domain.BSort;
import com.xhh.nphm.system.domain.ScodeSmallEty;
import com.xhh.nphm.system.service.IAppealCateService;
import com.xhh.nphm.system.service.IScodeSmallService;
import com.xhh.nphm.system.service.ISortService;
import com.xhh.nphm.system.service.impl.CommonServiceImpl;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.print.DocFlavor;
import java.util.*;

@RestController
@RequestMapping("/system/content")
public class ContentManageController extends BaseController {
    private String prefix = "system/content";
    @Autowired
    private IScodeSmallService scodeSmallService;
    @Autowired
    private CommonServiceImpl commonService;
    @Autowired
    private ISortService sortService;
    @Autowired
    private IAppealCateService appealCateService;

    /**
     * 交办意见管理 列表页面
     * @return
     */
    @GetMapping("/xdealDesc")
    public ModelAndView xdealDesc(){
        return new ModelAndView(prefix+"/xdealDesc");
    }

    /**
     * 交办意见管理 列表数据
     * @return
     */
    @PostMapping("xdealDescJson")
    public TableDataInfo xdealDescJson(ScodeSmallEty scodeSmallEty) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy2());
            if(StringUtils.isEmpty(orderBy)) {
                orderBy = "CSOrd asc";
            }
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
        else {
            pageNum = 1;
            pageSize = 5;
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy2());
            if(StringUtils.isEmpty(orderBy)) {
                orderBy = "CSOrd asc";
            }
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
        List<ScodeSmallEty> list = scodeSmallService.xdealDescJson(scodeSmallEty);
        return getDataTable(list);
    }

    /**
     * 交办意见 新增页面
     * @return
     */
    @GetMapping("/add")
    public ModelAndView add() {
        return new ModelAndView(prefix+"/add");
    }
    /**
     * 交办意见新增数据
     */
    @PostMapping("addJson")
    @RequestBody
    public AjaxResult addJson(ScodeSmallEty scodeSmallEty) {
        List<Map> opinion = commonService.findOpinion();
        for (Map map : opinion) {
            if (scodeSmallEty.getCsvalue().equals(map.get("CSValue"))){
                return error("编号重复,请重新输入");
            }
        }
        scodeSmallEty.setCodeBig("opinion");
        return toAjax(scodeSmallService.save(scodeSmallEty));
    }

    /**
     * 交办意见 编辑页面
     * @param csvalue
     * @param map
     * @return
     */
    @GetMapping("/edit/{csvalue}")
    public ModelAndView edit(@PathVariable String csvalue, ModelMap map) {
        ScodeSmallEty scodeSmallEty=scodeSmallService.selectCsValue(csvalue);
        map.put("scodeSmall",scodeSmallEty);
        return new ModelAndView(prefix+"/edit");
    }
    @PostMapping("editJson")
    @RequestBody
    public AjaxResult editJson(ScodeSmallEty scodeSmallEty) {
        UpdateWrapper<ScodeSmallEty> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("CSValue",scodeSmallEty.getCsvalue())
                .set("CSText",scodeSmallEty.getCstext())
                .eq("codeBig","opinion")
                .eq("useFlag",1)
                .eq("CSOrd",scodeSmallEty.getCsord());
        return toAjax(scodeSmallService.update(null,updateWrapper));
    }

    /**
     * 交办意见 根据 csvalue 单个删除和多选删除
     * @param ids
     * @return
     */
    @PostMapping("/remove")
    @RequestBody
    public AjaxResult remove(String ... ids) {
        return toAjax(scodeSmallService.deleteByIds(ids));
    }

    /**
     * 内容分类列表页面
     */
    @GetMapping("/contentSort")
    public ModelAndView contentSort() {
        return new ModelAndView(prefix+"/contentSort");
    }

    /**
     * 内容分类列表数据
     * @param bSort
     * @return
     */
    @PostMapping("contentSortJson")
    @ResponseBody
    public List<BSort> contentSortJson(BSort bSort) {
        List<BSort> list=sortService.contentSortJson(bSort);
        return list;
    }

    /**
     * 内容分类 新增页面
     */
    @GetMapping("/contentSortAdd/{codepk}")
    public ModelAndView contentSortAdd(@PathVariable String codepk,ModelMap map) {
        BSort bSort = sortService.selectByCodePk(codepk);
        map.put("sort",bSort);
        return new ModelAndView(prefix+"/contentSortAdd");
    }
    /**
     * 内容分类 新增数据
     */
    @PostMapping("contentSortAddJson")
    public AjaxResult contentSortAddJson(BSort bSort) {
        if ("1".equals(sortService.checkSortNameUnique(bSort))) {
            return error("新增内容分类'" + bSort.getSortname() + "'失败，内容已存在");
        }
        bSort.setProgramcode("CntSort");
        bSort.setBringtime(new Date());
        bSort.setIsdel(0);
        return toAjax(sortService.save(bSort));
    }
    /**
     * 内容分类 编辑页面
     */
    @GetMapping("/contentSortEdit/{codepk}")
    public ModelAndView contentSortEdit(@PathVariable String codepk,ModelMap map) {
        BSort bSort=sortService.selectByCodePk(codepk);
        map.put("parentName",sortService.selectByCodePk(bSort.getCodeparent())==null? new BSort() : sortService.selectByCodePk(bSort.getCodeparent()));
        map.put("sort",bSort);
        return new ModelAndView(prefix+"/contentSortEdit");
    }

    /**
     * 内容分类 编辑数据
     * @param bSort
     * @return
     */
    @PostMapping("contentSortEditJson")
    @RequestBody
    public AjaxResult contentSortEditJson(BSort bSort) {
        if ("1".equals(sortService.checkSortNameUnique(bSort))) {
            return error("修改内容分类'" + bSort.getSortname() + "'失败，内容已存在");
        } else if (bSort.getCodeparent().equals(bSort.getCodepk())) {
            return error("修改内容分类'" + bSort.getSortname()+ "'失败，上级部门不能是自己");
        }
        UpdateWrapper<BSort> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("CodePK",bSort.getCodepk())
                .set("CodeParent",bSort.getCodeparent())
                .set("SortName",bSort.getSortname())
                .set("OrdNum",bSort.getOrdnum())
                .eq("CodePK",bSort.getCodepk());
        return toAjax(sortService.update(null,updateWrapper));
    }

    /**
     * 根据 codepk 单个删除和多选删除
     * @param
     * @return
     */
    @RequestMapping("/removeContentSort/{codepk}")
    public AjaxResult removeContentSort(@PathVariable String codepk) {
        if (sortService.selectSortCount(codepk) > 0) {
            return AjaxResult.warn("存在下级部门,不允许删除");
        }
        return toAjax(sortService.deleteByCodePk(codepk));
    }
    /**
     * 校验内容名称
     */
    @PostMapping("/checkSortNameUnique")
    @ResponseBody
    public String checkSortNameUnique(BSort bSort) {
        return sortService.checkSortNameUnique(bSort);
    }
    /**
     * 选择部门树
     *
     * @param codepk    内容ID
     * @param excludeId 排除ID
     */
    @GetMapping(value = {"/selectSortTree/{codepk}", "/selectSortTree/{codepk}/{excludeId}"})
    public ModelAndView selectDeptTree(@PathVariable("codepk") String  codepk,
                                 @PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap) {
        mmap.put("sort", sortService.selectSortById(codepk));
        mmap.put("excludeId", excludeId);
        return new ModelAndView(prefix + "/contentSortTree");
    }
    /**
     * 加载内容分类列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        List<Ztree> ztrees = sortService.selectSortTree(new BSort());
        return ztrees;
    }

    /**
     * 加载内容分类列表树（排除下级）
     */
    @GetMapping("/treeData/{excludeId}")
    @ResponseBody
    public List<Ztree> treeDataExcludeChild(@PathVariable(value = "excludeId", required = false) Long excludeId) {
        BSort bSort= new BSort();
        bSort.setCodepk(excludeId+"");
        List<Ztree> ztrees = sortService.selectSortTreeExcludeChild(bSort);
        return ztrees;
    }

    /**
     * 常用语管理列表页面
     *  常用语:电话交办意见、坐席备注，信件处理意见
     * @return 视图
     */
    @GetMapping("/scodeSmallList")
    public ModelAndView scodeSmall(){
        return new ModelAndView(prefix + "/scodeSmallList");
    }

    /**
     * 常用语管理列表数据
     * @param scodeSmallEty 查询条件
     * @return 视图
     */
    @PostMapping("scodeSmallListJson")
    public TableDataInfo scodeSmallListJson(ScodeSmallEty scodeSmallEty){
        startPage();
        return getDataTable(scodeSmallService.scodeSmallListJson(scodeSmallEty));
    }

    /**
     * 新增常用语页面
     * @return 视图
     */
    @GetMapping("/addScodeSmall")
    public ModelAndView addScodeSmall(){
        return new ModelAndView(prefix + "/addScodeSmall");
    }

    /**
     * 新增常用语
     * @param scodeSmallEty 表单数据
     * @return 响应结果
     */
    @PostMapping("/addScodeSmall")
    public AjaxResult addScodeSmall(ScodeSmallEty scodeSmallEty){
        return toAjax(scodeSmallService.save(scodeSmallEty));
    }

    /**
     * 修改常用语
     * @param scodeSmallEty 表单数据
     * @return 响应结果
     */
    @PostMapping("/editScodeSmall")
    public AjaxResult editScodeSmall(ScodeSmallEty scodeSmallEty){
        return toAjax(scodeSmallService.updateById(scodeSmallEty));
    }

    /**
     * 修改常用语页面
     * @return 视图
     */
    @GetMapping("/editScodeSmall/{id}")
    public ModelAndView editScodeSmall(@PathVariable("id") Integer id,ModelMap map){
        map.addAttribute("scodeSmall",scodeSmallService.getById(id));
        return new ModelAndView(prefix + "/editScodeSmall");
    }

    /**
     * 根据id 进行多选删除 和单个删除 常用语
     *
     * @param ids 常用语id
     * @return 响应结果
     */
    @PostMapping("/removeScodeSmall")
    @ResponseBody
    public AjaxResult removeScodeSmall(String... ids) {
        return toAjax(scodeSmallService.removeByIds(Arrays.asList(ids)));
    }

    /**
     *以下新增 分类部分 appealCate
     * 2023/2/16
     */
    /**
     * 内容分类列表页面
     */
    @GetMapping("/contentAppealCate")
    public ModelAndView contentAppealCate() {

        return new ModelAndView(prefix+"/contentAppealCate");
    }

    /**
     * 内容分类列表数据
     * @param appealCate
     * @return
     */
    @PostMapping("contentAppealCateJson")
    @ResponseBody
    public List<AppealCate> contentAppealCateJson(AppealCate appealCate) {
        List<AppealCate> list=appealCateService.contentSortJson(appealCate);
        return list;
    }

    /**
     * 内容分类 新增页面
     */
    @GetMapping("/contentAppealCateAdd/{codepk}")
    public ModelAndView contentAppealCateAdd(@PathVariable String codepk,ModelMap map) {
        AppealCate appealCate = appealCateService.selectByCodePk(codepk);
        map.put("sort",appealCate);
        return new ModelAndView(prefix+"/contentAppealCateAdd");
    }
    /**
     * 内容分类 新增数据
     */
    @PostMapping("contentAppealCateAddJson")
    public AjaxResult contentAppealCateAddJson(AppealCate appealCate) {
        if ("1".equals(appealCateService.checkSortNameUnique(appealCate))) {
            return error("新增内容分类'" + appealCate.getSortname() + "'失败，内容已存在");
        }
        appealCate.setProgramcode("CntSort");
        appealCate.setBringtime(new Date());
        appealCate.setIsdel(0);
        return toAjax(appealCateService.save(appealCate));
    }
    /**
     * 内容分类 编辑页面
     */
    @GetMapping("/contentAppealCateEdit/{codepk}")
    public ModelAndView contentAppealCateEdit(@PathVariable String codepk,ModelMap map) {
        AppealCate appealCate=appealCateService.selectByCodePk(codepk);
        map.put("parentName",appealCateService.selectByCodePk(appealCate.getCodeparent())==null? new AppealCate() : appealCateService.selectByCodePk(appealCate.getCodeparent()));
        map.put("sort",appealCate);
        return new ModelAndView(prefix+"/contentAppealCateEdit");
    }

    /**
     * 内容分类 编辑数据
     * @param appealCate
     * @return
     */
    @PostMapping("contentAppealCateEditJson")
    @RequestBody
    public AjaxResult contentAppealCateEditJson(AppealCate appealCate) {
        if ("1".equals(appealCateService.checkSortNameUnique(appealCate))) {
            return error("修改内容分类'" + appealCate.getSortname() + "'失败，内容已存在");
        } else if (appealCate.getCodeparent().equals(appealCate.getCodepk())) {
            return error("修改内容分类'" + appealCate.getSortname()+ "'失败，上级部门不能是自己");
        }
        UpdateWrapper<AppealCate> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("CodePK",appealCate.getCodepk())
                .set("CodeParent",appealCate.getCodeparent())
                .set("SortName",appealCate.getSortname())
                .set("OrdNum",appealCate.getOrdnum())
                .eq("CodePK",appealCate.getCodepk());
        return toAjax(appealCateService.update(null,updateWrapper));
    }

    /**
     * 根据 codepk 单个删除和多选删除
     * @param
     * @return
     */
    @RequestMapping("/removeContentAppealCate/{codepk}")
    public AjaxResult removeContentAppealCate(@PathVariable String codepk) {
        if (appealCateService.selectSortCount(codepk) > 0) {
            return AjaxResult.warn("存在下级部门,不允许删除");
        }
        return toAjax(appealCateService.deleteByCodePk(codepk));
    }
    /**
     * 校验内容名称
     */
    @PostMapping("/checkAppealCateNameUnique")
    @ResponseBody
    public String checkAppealCateNameUnique(AppealCate appealCate) {
        return appealCateService.checkSortNameUnique(appealCate);
    }
    /**
     * 选择部门树
     *
     * @param codepk    内容ID
     * @param excludeId 排除ID
     */
    @GetMapping(value = {"/selectAppealCateTree/{codepk}", "/selectAppealCateTree/{codepk}/{excludeId}"})
    public ModelAndView selectDeptTree1(@PathVariable("codepk") String  codepk,
                                       @PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap) {
        mmap.put("sort", appealCateService.selectSortById(codepk));
        mmap.put("excludeId", excludeId);
        return new ModelAndView(prefix + "/contentAppealCateTree");
    }
    /**
     * 加载内容分类列表树
     */
    @GetMapping("/treeData1")
    @ResponseBody
    public List<Ztree> treeData1() {
        List<Ztree> ztrees = appealCateService.selectSortTree(new AppealCate());
        return ztrees;
    }

    /**
     * 加载内容分类列表树（排除下级）
     */
    @GetMapping("/treeData1/{excludeId}")
    @ResponseBody
    public List<Ztree> treeDataExcludeChild1(@PathVariable(value = "excludeId", required = false) Long excludeId) {
        AppealCate appealCate= new AppealCate();
        appealCate.setCodepk(excludeId+"");
        List<Ztree> ztrees = appealCateService.selectSortTreeExcludeChild(appealCate);
        return ztrees;
    }

}
